package com.starbooks.tmail.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class UploadController {

  @GetMapping("/upload")
  public String upload1() {
    return "upload";
  }

  @PostMapping("/upload")
  public String upload2(@RequestParam("file") MultipartFile file, HttpServletRequest req) throws IOException {
    file.transferTo(new File("C:\\Users\\ASUS\\Desktop\\uploads\\", UUID.randomUUID() + "upload.png"));
    return "upload";
  }

  // 处理上传文件结果
  private Map<String, Object> dealResultMap(boolean success, String msg) {
    Map<String, Object> result = new HashMap<String, Object>();
    result.put("success", success);
    result.put("msg", msg);
    return result;
  }


  // 使用HttpServletRequest作为参数
  @PostMapping("/upload1")
  @ResponseBody
  public String uploadRequest(HttpServletRequest request) {
    MultipartHttpServletRequest mreq = null;
    // 强制转换为MultipartHttpServletRequest接口对象
    if (request instanceof MultipartHttpServletRequest) {
      mreq = (MultipartHttpServletRequest) request;
    } else {
      return "上传失败";
    }
    // 获取MultipartFile文件信息
    MultipartFile mf = mreq.getFile("file");
    // 获取源文件名称
    String fileName = mf.getOriginalFilename();
    File file = new File(fileName);
    try {
      // 保存文件
      mf.transferTo(file);
    } catch (Exception e) {
      e.printStackTrace();
      return "上传失败";
    }
    return "上传成功";
  }

  // 使用Spring MVC的MultipartFile类作为参数
  @PostMapping("/upload2")
  @ResponseBody
  public String uploadMultipartFile(MultipartFile file) {
    String fileName = file.getOriginalFilename();
    File dest = new File(fileName);
    try {
      file.transferTo(dest);
    } catch (Exception e) {
      e.printStackTrace();
      return"上传失败";
    }
    return "上传成功";
  }


  // uploadPart方法是使用Servlet的API，可以使用其write方法直接写入文件，这也是推荐的方式
  @PostMapping("/upload3")
  @ResponseBody
  public String uploadPart(Part file) {
    // 获取提交文件名称
    String fileName = file.getSubmittedFileName();
    try {
      file.write(fileName);
    } catch (Exception e) {
      e.printStackTrace();
      return "上传失败";
    }
    return "上传成功";
  }


  private boolean isImage(MultipartFile file){
    return file.getContentType().startsWith("image");
  }

  private static String getFileExt(String filename){
    return filename.substring(filename.lastIndexOf("."));
  }
}
